﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

using System.IO;

using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.ADF.Connection;
using ESRI.ArcGIS.ADF.IMS;


public partial class GetMap : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        Response.Charset = "utf-8";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

        string mapTypeFlag = "";
        string ExtentBox = "";
        string mapLeft, mapRight, mapTop, mapBottom;
        string ServiceName = "";
        string imgWith, imgHeight;
        string strGraduations = "";
        string strLabels = "";
        string strColors = "";
        string modelName = "";
        string strParamA = "";
        string strParamB = "";
        double param_a = 0.0;
        double param_b = 0.0;
        string ImageId = "";
        string SelectedRS = "";// "NDVI_";
        string checkedLayers = ""; 

        string mapBox = "";

        string LayerName = "";//11-18日添加，用于AXL中的LAYER的name属性

        string strResultXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "\n";
        string resultUrl = "";

        //获取request参数
        ServiceName = Request.QueryString[0].ToString();//地图服务名
        mapTypeFlag = Request.QueryString[1].ToString();//地图服务请求类型（map和legend）
        ExtentBox = Request.QueryString[2].ToString();//地图的地理范围
        imgWith = Request.QueryString[3].ToString();//地图的图片宽度
        imgHeight = Request.QueryString[4].ToString();//地图的图片高度

        strGraduations = Request.QueryString[5].ToString();//长势的分级刻度List
        strLabels = Request.QueryString[6].ToString();//长势的分级Label List
        strColors = Request.QueryString[7].ToString();//长势的分级Label List

        modelName = Request.QueryString[8].ToString();//所采用的模型名称
        strParamA = Request.QueryString[9].ToString();//模型的参数a
        strParamB = Request.QueryString[10].ToString();//模型的参数b
        if (strParamA.Length > 0) param_a = Convert.ToDouble(strParamA);
        if (strParamB.Length > 0) param_b = Convert.ToDouble(strParamB);

        ImageId = Request.QueryString[11].ToString();//用于长势分级的影像ID

        LayerName = Request.QueryString[12].ToString();////11-18日添加，用于AXL中的LAYER的name属性
        SelectedRS = Request.QueryString[13].ToString(); //2009-4-9，用于选择植被指数数据源
        ImageId = SelectedRS + "_" + ImageId;
        checkedLayers = Request.QueryString[14].ToString();



        //获取常用的系统变量
        string javaHome = System.Configuration.ConfigurationManager.AppSettings["JAVA_HOME"]; //Environment.GetEnvironmentVariable("JAVA_HOME", System.EnvironmentVariableTarget.Machine);
        string arcimsServer = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER"];
        string arcimsAdmin = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_ADMIN"];
        string arcimsPwd = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_PWD"];

        string arcimsServerInternet = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER_INTERNET"];
        string arcimsServerIntranet = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER_INTRANET"];
        string imageUrl = "http://" + arcimsServer + "//output//";
        string imageUrlIntranet = "http://" + arcimsServerIntranet + "//output//";
        string imageUrlInternet = "http://" + arcimsServerInternet + "//output//";

        string[] ExtentArray = ExtentBox.Split(',');

        Graduations current_graduation = new Graduations();
        if (strGraduations.Length > 0)
        {
            string[] strGraduationArray = strGraduations.Split(',');
            int nGraduations = strGraduationArray.Length - 1;
            //******************************************************12-9日添加
            if (strGraduationArray[0] == "system")
            {
                nGraduations = int.Parse(strGraduationArray[1]);
                current_graduation.GetGraduations(LayerName, nGraduations, ref strGraduations);

                strGraduationArray = strGraduations.Split(',');
                nGraduations = strGraduationArray.Length - 1;
            }

            if (strLabels == "system")
            {
                current_graduation.GetLablesGraduations(LayerName, nGraduations, ref strLabels);
            }
            if (strColors == "system")
            {
                switch (nGraduations)
                {
                    case 2:
                        strColors = ImsColor.lightgreen + "," + ImsColor.darkgreen;
                        break;
                    case 3:
                        strColors = ImsColor.yellow + "," + ImsColor.lightgreen + "," + ImsColor.darkgreen;
                        break;
                    case 4:
                        strColors = ImsColor.blue + "," + ImsColor.yellow + "," + ImsColor.red + "," + ImsColor.darkgreen;
                        break;
                    case 5:
                        strColors = ImsColor.red + "," + ImsColor.darkorange + "," + ImsColor.yellow + "," + ImsColor.lightgreen + "," + ImsColor.darkgreen;
                        break;
                    default:
                        strColors = "";
                        break;
                }
            }
            //******************************************************
            string[] strLabelArray = strLabels.Split(',');
            string[] strColorArray = strColors.Split(',');//设置的颜色

            int nLabels = strLabelArray.Length - 1;
            for (int i = 0; i < nLabels; i++)
            {
                if (strGraduationArray[i + 1].Length == 0)
                    strLabelArray[i] = "> " + strGraduationArray[i] + " " + strLabelArray[i];
                else
                    strLabelArray[i] = strGraduationArray[i] + "~" + strGraduationArray[i + 1] + " " + strLabelArray[i];
                strColorArray[i] = Utility.hexToRGB(strColorArray[i]);//
            }
            //strLabelArray[i] = strGraduationArray[i] + "~" + strGraduationArray[i + 1] + " " + strLabelArray[i];
            //strColorArray[i] = Utility.hexToRGB(strColorArray[i]);


            double[] AgriGraduations = new double[nGraduations];
            string[] RSIndexGraduations = new string[nGraduations];


            if (modelName == "LinerModel")
            {
                for (int i = 0; i < nGraduations; i++)
                {
                    AgriGraduations[i] = double.Parse(strGraduationArray[i]);
                    RSIndexGraduations[i] = Convert.ToString(Math.Round((AgriGraduations[i] - param_a) / param_b, 3));
                }
 
            }
            else if (modelName == "ExpModel")
            {
                for (int i = 0; i < nGraduations; i++)
                {
                    AgriGraduations[i] = double.Parse(strGraduationArray[i]);
                    RSIndexGraduations[i] =  Convert.ToString(Math.Round(Math.Log((AgriGraduations[i] - param_a) / param_b), 3));
                }
            }
            else if (modelName == "LogModel")
            {
                for (int i = 0; i < nGraduations; i++)
                {
                    AgriGraduations[i] = double.Parse(strGraduationArray[i]);
                    RSIndexGraduations[i] =  Convert.ToString(Math.Round(Math.Exp((AgriGraduations[i] - param_a) / param_b), 3));
                }
            }


            MapConfig myMapConfig = new MapConfig();
            string mapConfigAxl = "";
            if (LayerName != "undefined")
            {
                if (LayerName == "Drought")
                {
                    if (mapTypeFlag == "IMSLEGEND") //090521
                    {
                        mapConfigAxl = myMapConfig.CreateSimpleAxl_Drought(RSIndexGraduations, strLabelArray, strColorArray, ImageId,  checkedLayers);
                        Response.Write(mapConfigAxl);
                        return;
                    }
                    else
                    {
                        mapConfigAxl = myMapConfig.CreateSimpleAxl_Drought(RSIndexGraduations, strLabelArray, strColorArray, ImageId,  checkedLayers);
                    }
                }
                else
                {
                    mapConfigAxl = myMapConfig.CreateSimpleAxl(RSIndexGraduations, strLabelArray, strColorArray, ImageId, LayerName);
                }
            }
            else
            {
                mapConfigAxl = myMapConfig.CreateSimpleAxl(RSIndexGraduations, strLabelArray, strColorArray, ImageId);
            }
            

            string ArcXML_Location = System.Configuration.ConfigurationManager.AppSettings["DEFAULT_ARCXML_LOCATION"];

            string axlFileFullName = ArcXML_Location + ServiceName + ".axl";
            string removeServiceFile = ArcXML_Location + "RemoveService.xml";
            string createServiceFile = ArcXML_Location + "CreateService.xml";

            //string adminServiceXmlFileName = ArcXML_Location + "AdminService.xml";
            string batFileName = ArcXML_Location + "AdminService.bat";
            string ArcIMSServiceLocation = "http://" + arcimsServer;

            //******************************************************************
            //得到当前地图配置文件的范围，12-4日
            //XmlDocument mydocument = new XmlDocument();
            //mydocument.LoadXml(mapConfigAxl);
            //XmlNodeList nodeList = mydocument.GetElementsByTagName("ENVELOPE");
            //if(nodeList!=null)
            //{
            //    mapBox = nodeList[0].Attributes[0].Value + "," + nodeList[0].Attributes[1].Value + "," + nodeList[0].Attributes[2].Value + "," + nodeList[0].Attributes[3].Value;
            //}
            
            //******************************************************************

            try
            {
                StreamWriter rw = File.CreateText(axlFileFullName);
                rw.Write(mapConfigAxl);
                rw.Flush();
                rw.Close();

                //string imageUrl = "http://" + arcimsServer + "//output//";

                ////=====Yang 2009.5.7=========================
                ////用于记录服务器外网地址
                //string arcimsServerInternet = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER_INTERNET"];
                ////=====Yang 2009.5.7=========================
                //string imageUrl = "http://" + arcimsServer + "//output//";
                //if (Request.RawUrl.ToLower().IndexOf("www") > -1)
                //{
                //    imageUrl = "http://" + arcimsServerInternet + "//output//";
                //}



                AdminService myAdminService = new AdminService();
                bool isCreateRemoveXml = myAdminService.createRemoveServiceXml(ServiceName, removeServiceFile);
                bool isCreateAddXml = myAdminService.createAddServiceXml(imageUrl, ServiceName, axlFileFullName, createServiceFile);

                ESRI.ArcGIS.ADF.Connection.IMS.TCPConnection pConn = new ESRI.ArcGIS.ADF.Connection.IMS.TCPConnection(arcimsServer, 5300);

                pConn.ServiceName = "catalog";
                IMSRequest pImsRequest = new IMSRequest();
                string getServiceListRequest = pImsRequest.getServiceList();
                IMSResponse pResponse = new IMSResponse();
                string[] serviceList = pResponse.getServiceNameList(getServiceListRequest, pConn);
                if (serviceList != null)
                {
                    for (int i = 0; i < serviceList.Length; i++)
                    {
                        if (serviceList[i] == ServiceName)
                        {
                            bool isRemoveSuccess = myAdminService.Excute(batFileName, removeServiceFile, ArcIMSServiceLocation, javaHome, arcimsAdmin, arcimsPwd);
                            break;
                        }
                    }
                }

                bool isAddSuccess = myAdminService.Excute(batFileName, createServiceFile, ArcIMSServiceLocation, javaHome, arcimsAdmin, arcimsPwd);

                if (!isAddSuccess)
                {
                    strResultXml += "<URLs>" + "\n";
                    strResultXml += "<URL>" + resultUrl + "</URL> \n";
                    strResultXml += "</URLs>" + "\n";
                    Response.Write(strResultXml);
                    return;
                }


            }
            catch (FieldAccessException ex)
            {
                throw ex;
            }
        }       


        //string[] ExtentArray = ExtentBox.Split(',');
        mapLeft = ExtentArray[0];
        mapRight = ExtentArray[1];
        mapTop = ExtentArray[2];
        mapBottom = ExtentArray[3];
        mapBox = mapLeft + "," + mapTop + "," + mapTop + "," + mapBottom;


        string XmlString = "";
        XmlString += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        XmlString += "\n" + "<ARCXML version=\"1.1\">";
        XmlString += "\n" + "<REQUEST>";
        XmlString += "\n" + "<GET_IMAGE>";
        XmlString += "\n" + "<PROPERTIES>";
        XmlString += "\n" + "<IMAGESIZE width=\"" + imgWith + "\" height=\"" + imgHeight + "\"/>";
        XmlString += "\n" + "<ENVELOPE minx=\"" + mapLeft + "\" miny=\"" + mapTop + "\" maxx=\"" + mapRight + "\" maxy=\"" + mapBottom + "\" />";
        if (mapTypeFlag == "IMSLEGEND")
        {
            XmlString += "\n" + "<LEGEND display=\"true\" width=\"240\" autoextend=\"true\" title=\"\" font=\"黑体\" titlefontsize=\"14\" titlefontstyle=\"bold\" layerfontsize=\"12\" layerfontstyle=\"bold\" valuefontsize=\"10\" cellspacing=\"8\" backgroundcolor=\"255,255,255\" />";
            XmlString += "\n" + "<DRAW map=\"false\" />";
        }
        else
        {
            XmlString += "\n" + "<LEGEND display=\"false\" />";
        }
        XmlString += "\n" + "</PROPERTIES>";
        XmlString += "\n" + "</GET_IMAGE>";
        XmlString += "\n" + "</REQUEST>";
        XmlString += "\n" + "</ARCXML>";


        ESRI.ArcGIS.ADF.Connection.IMS.TCPConnection pCon = new ESRI.ArcGIS.ADF.Connection.IMS.TCPConnection(arcimsServer, 5300);
        pCon.ServiceName = ServiceName;
        IMSResponse pImsResponse = new IMSResponse();
        
        if (mapTypeFlag == "IMSLEGEND")
        {
            resultUrl = pImsResponse.GetImageResponse(XmlString, pCon, "legend");
        }
        else
        {
            resultUrl = pImsResponse.GetImageResponse(XmlString, pCon, "map");
        }


        if (Request.Url.Host.ToLower().IndexOf("www") > -1)
        {
            //resultUrl = resultUrl.Replace(arcimsServer, arcimsServerInternet);
            resultUrl = resultUrl.Replace(imageUrl, imageUrlInternet);

        }
        else
        {
            resultUrl = resultUrl.Replace(imageUrl, imageUrlIntranet);
        }



        strResultXml += "<URLs>" + "\n";
        strResultXml += "<URL>" + resultUrl + "</URL> \n";
        if(mapBox!="")
        {
            strResultXml += "<ENVELOPE>" + mapBox + "</ENVELOPE> \n";//12-4日
        }        
        strResultXml += "</URLs>" + "\n";
        Response.Write(strResultXml);
    }
}
